<?php

/**
 * 服务指南违规处理
 */
namespace Beerus\Modules\DesignerService\Controllers;

use App\Http\Controllers\Controller;
use Doraemon\model\DesignerService\DesignerServiceViolation;
use Doraemon\model\Member;
use Doraemon\service\DesignerService\ServiceViolationService;
use Doraemon\tools\ParamsCheck;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Widgets\Tab;
use Illuminate\Support\MessageBag;
use Encore\Admin\Widgets\Form;

class ServiceViolationController extends Controller
{
	const PAGE_SIZE = 20;

	public function __construct()
	{
		parent::__construct();
		Admin::script('$(".pjax-container").attr("id","pjax-container");');
	}

	public function index(Request $request, Content $content)
	{
		$request_data = $request->all();

		$page_size = $request->input('per_page', self::PAGE_SIZE);
		$page = $request->input('page', 1);

		$condition['data_status'] = DesignerServiceViolation::STATUS_NORMAL;
		if (!empty($request_data['uid'])) {
			$condition['uid'] = $request_data['uid'];
		}
        if (!empty($request['nick'])) {
            $uid = Member::get('uid', ['nick' => $request['nick']]);
            if ($uid) {
                $condition['uid'] = $uid;
            } else {
                $condition['uid'] = -1;
            }
        }

		$condition['LIMIT'] = [
			($page - 1) * $page_size,
			$page_size
		];

		$lists = DesignerServiceViolation::select('*', $condition);

		$total = 0;
		if (!empty($lists)) {
			unset($condition['ORDER']);
			unset($condition['LIMIT']);
			$total = DesignerServiceViolation::count($condition);
		}

		$gridModel = new pGridDataModel($lists, $total, [
			'perPage' => $page_size
		]);
		$gridList = Admin::grid(
			$gridModel,
			function (Grid $grid) use ($gridModel) {
				$grid->paginate($gridModel->getPerPage());
				$grid->disableExport();
				$grid->disableRowSelector();

				$grid->filter(function (Grid\Filter $filter) {
					$filter->disableIdFilter();
					$filter->column(1 / 2, function ($filter) {
                        $filter->equal('uid', '设计师UID')->placeholder('请输入uid');
					});
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('nick', '设计师昵称')->placeholder('请输入设计师昵称');
                    });
					$filter->expand();
				});

				$grid->column('id', 'ID');
				$grid->column('uid', '设计师UID')->display(function () {
					return $this->uid;
				});
                $grid->column('nick', '设计师昵称')->display(function () {
                    return Member::get('nick', ['uid' => $this->uid]);
                });
                $grid->column('violation_time', '禁用时间')->display(function () {
                    return date('Y-m-d H:i:s', $this->start_time) . '—' . date('Y-m-d H:i:s', $this->end_time);
                });
				$grid->column('add_time', '创建时间')->display(function () {
					return date('Y-m-d H:i', $this->add_time);
				});
				$grid->column("admin_id", '操作人')->display(function () {
					if (!$this->admin_id) {
						return '-';
					} else {
						return Admin::user()->find($this->admin_id)->name;
					}
				});
			}
		);

		$tab = new Tab();
		$tab->add('设计师服务违规列表', $gridList->render());
		$content->row($tab);
		return $content
			->header('设计师服务违规列表')
			->breadcrumb(['text' => '设计师服务违规列表']);
	}

	public function edit(Request $request, Content $content, $id = 0)
	{
		$request = $request->all();

		if ($id == 0) {
			$is_create = true;
			$header = '添加服务违规';
		} else {
			$is_create = false;
			$header = '修改服务违规';
		}

		$tab = new Tab();
		$tab->add('服务违规处理', self::editAction($request, $id, $is_create));
		return $content->header($header)
			->breadcrumb([
				'text' => '服务违规列表',
				'url' => route('service_violation.list')
			], ['text' => $header])->row($tab);
	}

	public function editAction($request, $id = 0, $is_create = false)
	{
		if ($is_create) {
			$data = [];
			$form = new Form($data);
		} else {
			$data = DesignerServiceViolation::get('*', ['id' => $id]);
            $data['start_time'] = date('Y-m-d H:i:s', $data['start_time']);
            $data['end_time'] = date('Y-m-d H:i:s', $data['end_time']);
			$form = new Form($data);
			$form->hidden('id');
		}
		$form->text('uid', '设计师uid')->setWidth(4, 2)->required('不能为空');
        $form->datetimeRange('start_time', 'end_time', '禁用时间')->required('不能为空');
        $form->textarea('remark', '备注')->setWidth(4, 2)->attribute('maxlength',100);
        $form->action('/admin/DesignerService/service_violation/save');

		return $form->render();
	}

	public function submit(Request $request)
	{
		$request = $request->all();
        if (!ParamsCheck::isPositiveNumber($request['uid'])) {
            $error = new MessageBag([
                'title' =>'uid格式错误'
            ]);
            return back()->with(compact('error'));
        }
        $userInfo = Member::getUserInfo($request['uid']);
        if (empty($userInfo)) {
            $error = new MessageBag([
                'title' =>'uid不存在'
            ]);
            return back()->with(compact('error'));
        }
        if ($userInfo['type'] != Member::AUTH_USER_DESIGNER) {
            $error = new MessageBag([
                'title' =>'uid非设计师'
            ]);
            return back()->with(compact('error'));
        }

        $request['start_time'] = strtotime($request['start_time']);
        $request['end_time'] = strtotime($request['end_time']);

        if ($request['start_time'] >= $request['end_time']) {
            $error = new MessageBag([
                'title' =>'禁用结束时间应大于开始时间'
            ]);
            return back()->with(compact('error'));
        }
        $where['uid'] = $request['uid'];
        $where['data_status'] = DesignerServiceViolation::STATUS_NORMAL;
        if (!empty($request['id'])) {
            $where['id[!]'] = $request['id'];
        }
        $violation = DesignerServiceViolation::get('*',$where);
        if (!empty($violation)) {
            $error = new MessageBag([
                'title' =>'该uid已被禁用'
            ]);
            return back()->with(compact('error'));
        }

		$data = [
			'uid' => $request['uid'],
			'start_time' => $request['start_time'],
			'end_time' => $request['end_time'],
			'remark' => $request['remark'],
			'admin_id' => Admin::user()->id,
		];

		if (!empty($request['id'])) {
			$data['edit_time'] = time();
			$rs = DesignerServiceViolation::update($data, [
				'id' => $request['id']
			]);
		} else {
			$data['add_time'] = time();
			$rs = DesignerServiceViolation::insert($data);
		}

		if ($rs) {
			if (!empty($request['id'])) {
				$title = '修改成功';
			} else {
				$title = '添加成功';
			}
			$success = new MessageBag([
				'title' => $title
			]);
			return redirect('/admin/DesignerService/service_violation')->with(compact('success'));
		} else {
			if (!empty($request['id'])) {
				$title = '修改失败';
			} else {
				$title = '添加失败';
			}
			$error = new MessageBag([
				'title' => $title
			]);
			return back()->with(compact('error'));
		}
	}

    public function delete($id)
    {
        $update_data = [
            'data_status' => DesignerServiceViolation::STATUS_DELETE,
            'admin_id' => Admin::user()->id,
        ];
        if (!DesignerServiceViolation::update($update_data, ['id' => $id])) {
            return response()->json([
                'status' => false,
                'message' => "删除失败",
            ]);
        }
        return response()->json([
            'status' => true,
            'message' => "删除成功",
        ]);
    }
}
